"""
This is the main game class, responsible for game logic.
"""
import pygame
from pygame.locals import *
import random
import sys
import os
import speech
import player
import config

class Game(object):
    def __init__(self):
        soundnames = []
        soundmap = {}
        speech.init_speech()
        pygame.init()
        self.window = pygame.display.set_mode((320, 200))
        pygame.display.set_caption("Pyngpong")
        self.clock = pygame.clock.Time()
    def LoadTheme(self):
        if os.path.exists("pyngpong.conf":
            self.SetTheme(config.getVar(configurationFile, "settings", "theme"))
        else:
            self.SetTheme("default")
    def SetTheme(self, theme):
        self.SoundTheme = theme
        if (os.name == "nt":
            self.soundTheme += "\\"
        else:
            self.soundTheme += "/"
        self.LoadSounds()
    def LoadSounds(self):
       for s in soundnames:
            soundmap[s] = pygame.mixer.Sound(self.soundTheme+s+".ogg")
    def LoadIdentica(self):
        self.identicaName = getVar(configurationFile, "identica", "username")
        self.identicaPassword = getVar(configurationFile, "identica", "password")
    def Run(self):
        """
        This is our main event loop; it is responsible for polling events, as well as waiting for other events to take place.
        """
        self.running = True
        while self.running:
            self.clock.tick(30) #30 fps should be good, we can increase later.
        #our loop will have had exited by now, since it runs while self.running is True.
        pygame.display.quit()
        pygame.quit()
        sys.exit(0)

    def HandleEvents(self):
        """
        This function should be called to handle any events, and pass them off to either a menu or process them, as part of the logic.
        """
        #we need to iterate through all events that are in the queue.
        for e in pygame.event.get():
            if e.type == QUIT:
                self.running = False
                return
            elif e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    self.running = False
                if self.menu:
                    if e.key == K_DOWN or e.key == K_RIGHT:
                        self.menu.NextItem()
                    elif (e.key == K_UP or e.key == K_LEFT:
                        self.menu.PreviousItem()
                    elif e.key == K_RETURN:
                        self.menu.ActivateItem()

    def AddSound(self, sound):
        soundnames += sound
    def PlaySound(self, sound):
        soundmap[sound].play()
